import datetime


def isoformat(time):
    '''
    将datetime或者timedelta对象转换成ISO 8601时间标准格式字符串
    :param time: 给定datetime或者timedelta
    :return: 根据ISO 8601时间标准格式进行输出
    '''
    if isinstance(time, datetime.datetime):  # 如果输入是datetime
        return time.isoformat();
    elif isinstance(time, datetime.timedelta):  # 如果输入时timedelta，计算其代表的时分秒
        hours = time.seconds // 3600
        minutes = time.seconds % 3600 // 60
        seconds = time.seconds % 3600 % 60
        return 'P%sDT%sH%sM%sS' % (time.days, hours, minutes, seconds) # 将字符串进行连接



d = datetime.datetime.now()

def day_get(d):
    oneday = datetime.timedelta(days=1)
    day = d - oneday
    date_from = datetime.datetime(day.year, day.month, day.day, 0, 0, 0)
    date_to = datetime.datetime(day.year, day.month, day.day, 23, 59, 59)
    return [date_from, date_to]

def week_get(d):
    dayscount = datetime.timedelta(days=d.isoweekday())
    dayto = d - dayscount
    sixdays = datetime.timedelta(days=6)
    dayfrom = dayto - sixdays
    date_from = datetime.datetime(dayfrom.year, dayfrom.month, dayfrom.day, 0, 0, 0)
    date_to = datetime.datetime(dayto.year, dayto.month, dayto.day, 23, 59, 59)
    print('---'.join([str(date_from), str(date_to)]))
    return [date_from, date_to]

def month_get(d):
    """
    返回上个月第一个天和最后一天的日期时间
    :return
    date_from: 2016-01-01 00:00:00
    date_to: 2016-01-31 23:59:59
    """
    # dayscount = datetime.timedelta(days=d.day)
    # dayto = d - dayscount
    # date_from = datetime.datetime(dayto.year, dayto.month, 1, 0, 0, 0)
    # date_to = datetime.datetime(dayto.year, dayto.month, dayto.day, 23, 59, 59)
    # print('---'.join([str(date_from), str(date_to)]))
    # return [date_from, date_to]

    #  修改之后返回今天以及三十天前的时间
    dayscount = datetime.timedelta(days=d.isoweekday())
    dayto = d - dayscount
    sixdays = datetime.timedelta(days=30)
    dayfrom = dayto - sixdays
    date_from = datetime.datetime(dayfrom.year, dayfrom.month, dayfrom.day, 0, 0, 0)
    date_to = datetime.datetime(dayto.year, dayto.month, dayto.day, 23, 59, 59)
    print('---'.join([str(date_from), str(date_to)]))
    return [date_from, date_to]




"""
if __name__ == '__main__':
    dtnow = datetime.datetime.now() # 获取现在时间
    print(isoformat(dtnow))

    dtpast = datetime.datetime(1990, 12, 31) # 获取过去某个时间点
    print(isoformat(dtpast))

    interval = dtnow - dtpast # 得到时间差
    print(interval)
    print(isoformat(interval))
--------------------- 
作者：TheOneGIS 
来源：CSDN 
原文：https://blog.csdn.net/theonegis/article/details/54425636 
版权声明：本文为博主原创文章，转载请附上博文链接！
"""